package com.ai.core.controller;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ai.core.cache.AICacheManager;
import com.ai.core.constant.GlobalConstant;
import com.ai.core.context.SpringContextUtil;
import com.ai.core.entity.InterfaceDef;
import com.ai.core.exception.RequestException;
import com.ai.core.pagemode.PublicRequestInfo;
import com.ai.core.pagemode.RequestInfo;
import com.ai.core.pagemode.ResponseInfo;
import com.alibaba.fastjson.JSON;

@Controller
public class CoreController extends CoreWebBinding {
	private AICacheManager aiCacheManager = AICacheManager.getInstance();

	private Map m_interface_def = null;

	@RequestMapping("/core")
	@ResponseBody
	public ResponseInfo core(String input,HttpServletRequest request) throws UnsupportedEncodingException {
		System.out.println(new String(input.getBytes("ISO-8859-1"),"UTF-8"));
		// 获取接口类型和接口标识
		ResponseInfo responInfo = new ResponseInfo();
		RequestInfo requestInfo = null;
		try {
			requestInfo = JSON.parseObject(input, RequestInfo.class);
			PublicRequestInfo publicRequestInfo = requestInfo.getPublicRequestInfo();
			String interfaceId = requestInfo.getInterfaceId();
			String transactionId = requestInfo.getTransactionId();
			if (publicRequestInfo == null)
				throw new RequestException("PublicRequestInfo is null", "9001");
			if (interfaceId == null)
				throw new RequestException("InterfaceId is null", "9002");
			if (transactionId == null)
				throw new RequestException("TransactionId is null", "9003");

			responInfo.setTransactionId(transactionId);
			if (m_interface_def == null) {
				m_interface_def = aiCacheManager.getMap(GlobalConstant.CACHE_INTERFACE_DEF);
			}
			if (!m_interface_def.containsKey(interfaceId)) {
				throw new RequestException("InterfaceId:" + interfaceId + " is not defined", "9004");
			}
			InterfaceDef interfaceDef = (InterfaceDef) m_interface_def.get(interfaceId);
			String beanName = interfaceDef.getBeanName();
			String methodName = interfaceDef.getMethodName();

			Map param = requestInfo.getParams();
			Object result = SpringContextUtil.invokeBeanMethod(beanName, methodName, new Object[] { param });
			responInfo.setRtnObj(result);
			responInfo.setCode("0000");
			responInfo.setMsg("success");
			responInfo.setReplyTransactionId(UUID.randomUUID().toString());
			return responInfo;
		} catch (RequestException e) {
			e.printStackTrace();
			responInfo.setCode(e.getCode());
			responInfo.setMsg(e.getMessage());
			return responInfo;
		} catch (Exception e) {
			e.printStackTrace();
			responInfo.setCode("9000");
			responInfo.setMsg(e.getMessage());
			return responInfo;
		}

	}
}
